package org.unique.weibooauthtest.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class AuthorizationAct extends Activity {
	OAuth oAuth;
	Config config;
	Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.authorization_view);
		oAuth = OAuth.getInstance();
		config = Config.getInstance();
		initWebView(oAuth.getRequestToken());
	}

	private void initWebView(String url) {
		WebView mWebView = (WebView) findViewById(R.id.oauth_webview);
		mWebView.clearCache(true);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new webViewClient());
		mWebView.setWebChromeClient(new webChromeClient());
		mWebView.loadUrl(url);
		final ProgressDialog mProgressDialog = new ProgressDialog(
				AuthorizationAct.this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setMessage("数据载入中，请稍后");

		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
				case 1:
					mProgressDialog.show();
					break;
				case 2:
					mProgressDialog.hide();
					break;
				}
			}
		};
	}

	class webViewClient extends WebViewClient {
		private int index = 0;
		private int index2 = 0;

		@Override
		public void onLoadResource(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onLoadResource(view, url);
			Log.i("onLoadResource", url);
			if (index2 == 0) {
				mHandler.sendEmptyMessage(0);
				index2++;
			}
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			super.onPageStarted(view, url, favicon);
			if (url.contains(config.callBackUrl) && index == 0) {
				index++;
				mHandler.sendEmptyMessage(1);
				Intent intent = new Intent(AuthorizationAct.this,
						ShowOauthResult.class);
				Uri uri = Uri.parse(url);
				intent.setData(uri);
				intent.putExtra("test", url);
				Log.i("url", "url=" + url);
				AuthorizationAct.this.startActivity(intent);
				AuthorizationAct.this.finish();
			}
		}
	}

	class webChromeClient extends WebChromeClient {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			// TODO Auto-generated method stub
			super.onProgressChanged(view, newProgress);
			if (newProgress == 100) {
				mHandler.sendEmptyMessage(2);
			}
		}
	}
}
